<template>
  <a-input
    v-model="value"
    placeholder="请选择"
    :allow-clear="allowClear"
    readonly
    class="input-modal"
    @clear.stop="handerClear"
    @search="select"
  >
    <template #append>
      <div class="apppend-box" @click="select">
        <icon-more />
      </div>
    </template>
  </a-input>
  <modal
    v-if="visible"
    :width="'1000'"
    :title="props.title"
    @modal-close="modalClose"
    @open="open"
    @handle-ok="handleOk"
  >
    <query-form
      ref="queryFormRef"
      :render-config="config"
      :render-keys="renderKeys"
      @search="searchHandle"
      @reset="resetHandle"
    />
    <table-container
      v-model:columns="columns"
      :loading="isLoading"
      :all-columns="allColumns"
      @refresh="getData"
    >
      <a-table
        :columns="columns"
        :data="renderData"
        :pagination="pagination"
        :loading="isLoading"
        :row-selection="{ type: 'radio' }"
        :row-key="rowKey"
        @page-change="pageChange"
        @page-size-change="pageSizeChange"
        @select="selectRow"
      >
        <template #secretLevel="{ record }">
          <secretLevel :record="record" />
        </template>
      </a-table>
    </table-container>
  </modal>
</template>

<!--新script-->
<script lang="ts" setup>
import { computed, ref, watch } from "vue";
import queryForm from "@/common/components/query-form/index.vue";
import tableContainer from "@/common/components/table-container/index.vue";
import secretLevel from "@/common/components/secret-level-info/index.vue";
import request from "@/utils/request/request";
import usePagination from "@/common/hooks/pagination";
import lodash from "lodash";
import { tableSearchObj } from "./categoryName";
import modal from "./modal.vue";

const props = defineProps({
  modelValue: {
    type: [String, Object]
  },
  /**
   * @param {string}
   * 回显值
   */
  labelValue: {
    type: String,
    default: ""
  },
  title: {
    type: String,
    default: ""
  },
  /**
   * @param {string}
   * 绑定数据的对象key
   */
  valueName: {
    type: String,
    default: "id"
  },
  /**
   * @param {string}
   * input 框的回显字段
   */
  labelName: {
    type: String,
    required: true,
    default: "name"
  },
  /**
   * @param {Array}
   * 自定义显示筛选字段
   */
  queryKeys: {
    type: Array,
    default: () => {
      return [];
    }
  },
  /**
   * @param {string}
   * 使用配置文件的类型
   */
  type: {
    type: String,
    required: true,
    default: ""
  },
  allowClear: {
    type: Boolean,
    default: true
  },
  defaultQuery: {
    type: Object,
    default: () => {
    }
  }
});
const { pagination, setCurrent, setPageSize, setTotal, queryPagination } =
  usePagination();

const queryFormRef = ref(null);
const selectedRow = ref({});
const renderKeys = ref<any>([]);
const rowKey = ref(tableSearchObj.rowKey || "id");
const config = computed(() => {
  return tableSearchObj.renderConfig;
});
const columns = computed(() => {
  return tableSearchObj.columns;
});
const emit = defineEmits([
  "update:modelValue",
  "change",
  "handerClear",
  "select",
  "handleOk"
]);
const visible = ref(false);
const value = ref(props.labelValue);
watch(
  () => props.queryKeys,
  (n: any) => {
    renderKeys.value.length = 0;
    if (n?.length > 0) {
      renderKeys.value = [...n];
    } else {
      renderKeys.value = [...tableSearchObj.renderKeys];
    }
  },
  { deep: true, immediate: true }
);
watch(
  () => props.labelValue,
  (n: any) => {
    value.value = n;
  },
  { deep: true, immediate: true }
);
watch(
  () => props.modelValue,
  (n: any) => {
    if (!n) {
      value.value = n;
    }
    // value.value = n;
  },
  { deep: true, immediate: true }
);
const select = () => {
  visible.value = true;
};
const handerClear = () => {
  emit("update:modelValue", null);
  emit("handerClear");
};
const modalClose = () => {
  visible.value = false;
};
const res = [];
const selectContent = ref();
const getParentRow = (rows: any[], parentId: any) => {
  // console.log(rows, childrenKey, parentId);
  let find = null;
  rows.forEach((item) => {
    if (item.id === parentId) {
      res.push(item);
    }
    find = getParentRow(item.children || [], parentId);
  });
  return find;
};
const selectRow = (keys: any, key: any, record: any) => {
  emit("select", record);
  selectedRow.value = record || {};
  value.value = record[props.labelName];
  getParentRow(renderData.value, record.parentId);
  selectContent.value = {
    ...record,
    categoryLv1: res[0].parentCategoryName,
    categoryLv1Code: res[0].parentCategoryCode,
    categoryLv1Id: res[0].parentId
  };
  // if (props.valueName.indexOf(',') > -1) {
  //   const names = props.valueName.split(',');
  //   const values: Array<string> = [];
  //   names.forEach((e) => {
  //     values.push(record[e]);
  //   });
  //   const valueName = values.join(',');
  //   emit('change', valueName);
  //   emit('update:modelValue', valueName);
  // } else if (typeof props.modelValue === 'string') {
  //   emit('change', value.value);
  //   emit('update:modelValue', value.value);
  // } else {
  //   emit('change', record);
  //   emit('update:modelValue', record);
  // }
};
const searchHandle = () => {
  getData();
};
const resetHandle = () => {
  setCurrent(1);
  getData();
};
const allColumns = lodash.cloneDeep(columns);
const isLoading = ref(true);
const renderData = ref<any[]>([]);

const getData = async () => {
  const params = {
    ...queryFormRef.value.getStatus(),
    ...queryPagination.value,
    ...props.defaultQuery
  };
  renderData.value = [];
  isLoading.value = true;
  const { data } = await request.get(tableSearchObj.api, {
    params
  });
  const arr = category(data);
  renderData.value = arr;
  setTotal(data.total);
  isLoading.value = false;
};
const category = (arr: any[]) => {
  arr.forEach(
    (v: {
      categoryHierarchy: string;
      disabled: boolean;
      children: string | any[];
    }) => {
      if (v.categoryHierarchy !== "三级") {
        v.disabled = true;
      }
      if (v.children && v.children?.length !== 0) {
        category(v.children);
      }
    }
  );
  return arr;
};
const pageChange = (val: number) => {
  setCurrent(val);
  getData();
};
const pageSizeChange = (val: number) => {
  setPageSize(val);
  getData();
};
const handleOk = () => {
  emit("update:modelValue", selectedRow.value[props.valueName]);
  emit("handleOk", selectContent.value);
};
const open = () => {
  getData();
};
</script>

<style lang="less" scoped>
.base-component {
  color: red;
}

.apppend-box {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.arco-table-pagination) {
  display: none;
}

:deep(.keep-name-all) {
  word-break: keep-all !important;
}
</style>
